# -*- coding: utf-8 
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.db.models import Q
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django_youtube_syncronizer.models import video_data

def get_videos(request):
    videoList = video_data.objects.all()
    paginacao = Paginator(videoList, 5)
    
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
        
    try:
        videoList = paginacao.page(page)
    except (EmptyPage, InvalidPage):
        videoList = paginacao.page(paginacao.num_pages)
    
    return render_to_response('raiz/videos/videos.html', locals(), context_instance = RequestContext(request))

def search_videos(request):
    
    query = request.GET.get('strBusca', '')
    if query: 
        qset = (
                Q(title__icontains=query) 
        )
        videoList = video_data.objects.filter(qset).distinct()
    else: 
        videoList = []
        
    if len(videoList) > 5: 
        paginacao = Paginator(videoList, 5) 
        try: 
            page = int(request.GET.get('page', '1'))
        except ValueError: 
            page = 1
        try: 
            videoList = paginacao.page(page) 
        except (EmptyPage, InvalidPage): 
            videoList = paginacao.page(paginacao.num_pages) 
    
    return render_to_response('raiz/videos/videos_search.html', locals(), context_instance = RequestContext(request))
    
  
